package com.ns002.yigou.quote.common.config;

import com.ns002.yigou.quote.common.app.HttpLoggingInterceptor;
import okhttp3.OkHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

/**
 * @Author xu
 * @Date 2017/7/26 0026 下午 9:24
 *
 * 网络相关配置
 */
@Configuration
public class NetworkConfig {

    private static final Logger httpLog = LoggerFactory.getLogger("http-network");

    /**
     * OKHTTP
     *
     * @return
     */
    @Bean("okHttpClient")
    public OkHttpClient okHttpClient(@Autowired HttpLoggingInterceptor httpLoggingInterceptor) {

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(2, TimeUnit.SECONDS)  //设置链接超时时间
                .readTimeout(10, TimeUnit.SECONDS)     //设置读取超时时间
                .writeTimeout(10, TimeUnit.SECONDS)    //设置写入超时时间
                .addInterceptor(httpLoggingInterceptor)
                //其他配置
                .build();

        return okHttpClient;
    }

    @Bean("httpLoggingInterceptor")
    public HttpLoggingInterceptor httpLoggingInterceptor() {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                httpLog.error(message);
            }
        });
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        return loggingInterceptor;
    }


}
